import { Pipe, PipeTransform } from '@angular/core';

@Pipe({name: 'convertMoney'})

export class ConvertMoneyPipe implements PipeTransform {
  transform(value): string {
    if (value) {
      let unit: number;
      let decade: number;
      let hundred: number;
      let firstStr = '';
      let secondStr = '';
      let fullStr = '';
      // 转成字符串并分割得到整数位和小数位
      const stringValue: string = value.toString();
      const integer: string = stringValue.split('.')[0];
      const decimal: string = stringValue.split('.')[1];
      // 先判断数字在哪个区间
      if (integer) {
        if (value === '0' || value === '0.') {
          firstStr = '0';
        } else if (value > 0 && value < 10) {
          hundred = null;
          decade = null;
          firstStr = integer.toString();
        } else if ( value < 100) {
          hundred = null;
          decade = Math.floor(value / 10);
          unit = Math.floor(value % 10);
          if (decade === 1) {
            if (unit === 0) {
              firstStr = '拾';
            } else {
              firstStr = '拾' + unit;
            }
          } else {
            if (unit === 0) {
              firstStr = decade + '拾';
            } else {
              firstStr = decade + '拾' + unit;
            }
          }
        } else {
          hundred = Math.floor(value / 100);
          decade = Math.floor(value / 10) % 10;
          unit = Math.floor(value % 10);
          if (unit === 0) {
            firstStr = hundred + '佰' + decade + '拾';
          } else {
          firstStr = hundred + '佰' + decade + '拾' + unit;
          }
        }
      } else {
        firstStr = '0';
      }
      if (decimal !== undefined && decimal !== '0' && decimal !== '00') {
        secondStr = '点' + decimal.toString();
      }
      // 前后相加
      fullStr = firstStr + secondStr;
      const reg0 = new RegExp( '0' , 'g' );
      const reg1 = new RegExp( '1' , 'g' );
      const reg2 = new RegExp( '2' , 'g' );
      const reg3 = new RegExp( '3' , 'g' );
      const reg4 = new RegExp( '4' , 'g' );
      const reg5 = new RegExp( '5' , 'g' );
      const reg6 = new RegExp( '6' , 'g' );
      const reg7 = new RegExp( '7' , 'g' );
      const reg8 = new RegExp( '8' , 'g' );
      const reg9 = new RegExp( '9' , 'g' );
      fullStr = fullStr.replace( reg0, '零');
      fullStr = fullStr.replace( reg1, '壹');
      fullStr = fullStr.replace( reg2, '贰');
      fullStr = fullStr.replace( reg3, '叁');
      fullStr = fullStr.replace( reg4, '肆');
      fullStr = fullStr.replace( reg5, '伍');
      fullStr = fullStr.replace( reg6, '陆');
      fullStr = fullStr.replace( reg7, '柒');
      fullStr = fullStr.replace( reg8, '捌');
      fullStr = fullStr.replace( reg9, '玖');
      return fullStr;
    } else {
      return '';
    }
  }
}
